const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generator = require('@babel/generator').default;
const t = require('@babel/types');
const { log } = require('console');
const fs = require('fs');

// 读取文件
const inputPath = "de_code2.js";
const outputPath = "de_de_code2.js";
const jscode = fs.readFileSync(inputPath, "utf-8");

function removeUnusedObjectAssignments(code) {
    const ast = parser.parse(code, {
        sourceType: 'unambiguous',
        allowReturnOutsideFunction: true,
        allowAwaitOutsideFunction: true,
        allowImportExportEverywhere: true,
    });

    // 收集所有变量引用
    const map = new Map();

    // 第一次遍历：收集所有被引用的变量
    traverse(ast, {
        ObjectExpression(path) {
            if(t.isAssignmentExpression(path.parentPath.node) && path.key == 'right'){
                console.log(111);
                map.set(path.parentPath.node.left.name,path.parentPath.node)  
            }
        }
    });
    console.log(111)
    traverse(ast,{
        CallExpression(path){
            name = path.node.callee.name
            if(map.has(name)){
                console.log(name)
                map.delete(name)
            }
        }
    })
    console.log(map)
    function logMapElements(value, key, map) {
        console.log(`m[${key}] = ${value}`);
        traverse(ast,{
            AssignmentExpression(path){
                if(path.node == value){
                    path.remove()
                }
            }
        })
    }

    //清理
    map.forEach(logMapElements)
    
    return ast;
}

// // 执行清理
const ast = removeUnusedObjectAssignments(jscode);
const output = generator(ast, { 
    comments: true,
    retainLines: false,
    compact: false
}).code;

// 写入文件
fs.writeFileSync(outputPath, output, "utf-8");
console.log("已完成清理，输出文件:", outputPath);